using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ItdavanyViewer
{
    public partial class MainForm : Form
    {
        private TreeNode root = null;

        public MainForm()
        {
            InitializeComponent();
            // Load icon
            this.MdiChildActivate += new EventHandler(MainForm_MdiChildActivate);            
        }
                
        public MainForm(string rootDir) : this()
        {
            SetRootDirectory(rootDir);
        }

        void MainForm_Shown(object sender, EventArgs e)
        {
            SelectRootDirectory();
        }

        void MainForm_MdiChildActivate(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null)
            {
                closeToolStripMenuItem.Enabled = true;
                closeAllToolStripMenuItem.Enabled = true;

                ItdavanyView view = (ItdavanyView)((XNAViewport)this.ActiveMdiChild).View;

                SetupTree(view.RootDirectory);
                panel1.BackColor = view.BackgroundColor;
            }
            else
            {
                closeToolStripMenuItem.Enabled = false;
                closeAllToolStripMenuItem.Enabled = false;
                itemView.Nodes.Clear();
            }
        }

        private bool SelectRootDirectory()
        {
            rootBrowser.SelectedPath = Directory.GetCurrentDirectory();

            if(rootBrowser.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    // proceed                    
                    SetRootDirectory(rootBrowser.SelectedPath);                                 
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    string defaultPath = 
                        Path.GetDirectoryName(
                        System.Reflection.Assembly.GetExecutingAssembly().Location
                        );
                    Directory.SetCurrentDirectory(defaultPath);

                    return false;
                }
                
                return true;
            }

            return false;
        }

        private void SetupTree(string dir)
        {
            itemView.Nodes.Clear();

            string name = Path.GetFileName(dir);
            if (name == "")
                name = Path.GetPathRoot(dir);

            root = new TreeNode(name);
            root.Tag = dir;
            itemView.Nodes.Add(root);
            CreateChildNodes(root);
        }
        
        private void SetRootDirectory(string dir)
        {
            XNAViewport viewport = new XNAViewport(new ItdavanyView(dir));
            viewport.MdiParent = this;

            Directory.SetCurrentDirectory(dir);

            //fileSystemWatcher.Path = dir;
            //fileSystemWatcher.EnableRaisingEvents = true;

            viewport.FormClosing += new FormClosingEventHandler(viewport_FormClosing);
            viewport.FormClosed += new FormClosedEventHandler(viewport_FormClosed);
            viewport.Show();
        }

        void viewport_FormClosed(object sender, FormClosedEventArgs e)
        {
            XNAViewport viewport = (XNAViewport)sender;            
            viewport.View.Dispose();
        }

        void viewport_FormClosing(object sender, FormClosingEventArgs e)
        {
            
        }       

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectRootDirectory();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {            
            //root = null;
            //fileSystemWatcher.EnableRaisingEvents = false;
            this.ActiveMdiChild.Close();
            //ItdavanyView.RootDirectory = null;
            //itemView.Nodes.Clear();
            //closeToolStripMenuItem.Enabled = false;
        }

        private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form child in this.MdiChildren)
                child.Close();
        }

        private void CreateChildNodes(TreeNode parent)
        {
            string path = (string)parent.Tag;

            string[] dirList = Directory.GetDirectories(path);
            string[] fileList = Directory.GetFiles(path);

            foreach (string singlePath in dirList)
            {
                TreeNode child = new TreeNode(Path.GetFileName(singlePath));
                child.Tag = singlePath;

                parent.Nodes.Add(child);
                try
                {
                    CreateChildNodes(child);
                }
                catch (Exception)
                {

                }
            }

            foreach (string singlePath in fileList)
            {
                switch(Path.GetExtension(singlePath).ToLower())
                {
                    case ".iod":
                    case ".xnb":
                        break;
                    default:
                        continue;
                }
                TreeNode child = new TreeNode(Path.GetFileName(singlePath));
                child.SelectedImageIndex = 2;
                child.ImageIndex = 2;
                child.Tag = singlePath;
                parent.Nodes.Add(child);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //Queue<ToolStripItem> queue = 
            //    new Queue<ToolStripItem>(MenuStrip.Items.Count);

            //foreach (ToolStripItem item in MenuStrip.Items)
            //{
            //    queue.Enqueue(item);
            //}

            //while (queue.Count != 0)
            //{
            //    ToolStripItem item = queue.Dequeue();
                
            //    if (item.GetType().Equals(typeof(ToolStripMenuItem)))
            //    {
            //        // now add event listener
            //        ToolStripMenuItem mItem = (ToolStripMenuItem)item;
            //        mItem.MouseEnter += new EventHandler(item_MouseHover);
                    

            //        foreach(ToolStripItem citem in mItem.DropDownItems)
            //            queue.Enqueue(citem);
            //    }
            //}
        }

        //void item_MouseHover(object sender, EventArgs e)
        //{
        //    if(sender.GetType().IsSubclassOf(typeof(ToolStripItem)))
        //    {
        //        ToolStripItem item = (ToolStripItem)sender;
        //        toolStripStatusLabel1.Text = item.Text;
        //    }
        //}

        private void MenuStrip_SelectedItemChanged(object sender, ToolStripItem item)
        {
            toolStripStatusLabel1.Text = (string)item.Tag;
        }

        private string GetFullPath(TreeNode node)
        {
            if (node == root)
                return "";
            else if (node.Parent == root)
                return node.Text;
            
            return GetFullPath(node.Parent) + @"\" + node.Text;
        }

        private void itemView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (e.Node.ImageIndex == 2)
                {
                    XNAViewport viewport = (XNAViewport)this.ActiveMdiChild;
                    ItdavanyView view = (ItdavanyView)viewport.View;
                    view.Close();
                    view.Read(GetFullPath(e.Node));
                    Itdavany.Objects.BaseObject obj = view.Object;

                    frameSelector.Items.Clear();
                    frameSelector.SelectedItem = null;
                    frameSelector.Enabled = false;

                    if (obj.GetType() == typeof(ItdavanyView.ItdavanyObject))
                    {
                        ItdavanyView.ItdavanyObject idvObj = 
                            (ItdavanyView.ItdavanyObject)obj;

                        frameSelector.Enabled = true;
                        foreach (string frmName in idvObj.Frames)
                        {
                            frameSelector.Items.Add(frmName);
                        }
                        frameSelector.SelectedItem = idvObj.CurrentFrame;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    ex.ToString(),
                    "Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void frameSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            ((ItdavanyView.ItdavanyObject)
                ((ItdavanyView)((XNAViewport)ActiveMdiChild).View).Object).CurrentFrame =
                frameSelector.SelectedItem.ToString();
        }
                
        private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
        {
            AddEntry(e.FullPath);
        }

        private void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            RemoveEntry(e.FullPath);
        }

        private void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
        {
            RemoveEntry(e.OldFullPath);
            AddEntry(e.FullPath);            
        }

        private void AddEntry(string path)
        {

        }

        private void RemoveEntry(string path)
        {

        }

        private void panel1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (colorDialog1.ShowDialog() == DialogResult.OK)
            {
                Color col = colorDialog1.Color;
                panel1.BackColor = col;
                ((ItdavanyView)((XNAViewport)ActiveMdiChild).View).BackgroundColor = col;
            }

        }
    }
}